import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter04/widget/swiper_image.dart';

class SwiperWidget extends StatefulWidget {
  final double width;
  final double height;
  final List<String> list;

  const SwiperWidget({
    super.key,
    this.width = double.infinity,
    this.height = 250,
    required this.list,
  });

  @override
  State<SwiperWidget> createState() => _SwiperWidgetState();
}

class _SwiperWidgetState extends State<SwiperWidget> {
  int _currentIndex = 0;
  List<Widget> pageList = [];
  late PageController _pageController;
  late Timer timer;

  @override
  void initState() {
    super.initState();
    _pageController = PageController(initialPage: _currentIndex);
    pageList = widget.list.map((e) => SwiperImagePage(src: e)).toList();

    timer = Timer.periodic(
      const Duration(seconds: 3),
      (t) {
        if (kDebugMode) {
          print("执行");
        }
        _pageController.animateToPage(
          (_currentIndex + 1) % pageList.length,
          duration: const Duration(microseconds: 200),
          curve: Curves.linear,
        );
      },
    );
  }

  @override
  void dispose() {
    super.dispose();
    timer.cancel();
    _pageController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        SizedBox(
          height: 250,
          child: PageView.builder(
            controller: _pageController,
            itemCount: pageList.length,
            onPageChanged: (index) {
              setState(() {
                _currentIndex = index;
              });
            },
            itemBuilder: (context, index) {
              return pageList[index];
            },
          ),
        ),
        Positioned(
          left: 0,
          right: 0,
          bottom: 2,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: List.generate(
              pageList.length,
              (index) {
                return Container(
                  width: 10,
                  height: 10,
                  margin: const EdgeInsets.all(5),
                  decoration: BoxDecoration(
                    color: _currentIndex == index ? Colors.blue : Colors.grey,
                    // borderRadius: BorderRadius.circular(5),
                    shape: BoxShape.circle,
                  ),
                ); //Text("${index + 1}");
              },
            ).toList(),
          ),
        )
      ],
    );
  }
}
